package com.jike.mahjong.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.geek.game.manager.agent.service.ConsumerService;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jike.mahjong.common.Constants;
import com.jike.mahjong.common.util.GsonUtil;
import com.jike.mahjong.common.util.HttpUtil;
import com.jike.mahjong.common.web.BaseController;
import com.jike.mahjong.common.web.BaseResult;
import com.jike.mahjong.model.Club;
import com.jike.mahjong.model.ClubPlayerMapping;
import com.jike.mahjong.model.Manager;
import com.jike.mahjong.model.NoticeMsg;
import com.jike.mahjong.model.Player;
import com.jike.mahjong.model.RequestModel;
import com.jike.mahjong.service.ClubService;
import com.jike.mahjong.service.PersonService;

@Controller
@RequestMapping("club")
public class ClubController extends BaseController{

	@Autowired
	private ClubService clubService;
	@Autowired
	private ConsumerService consumerService;

	@ResponseBody
    @RequestMapping(value="index.html",method = {RequestMethod.GET, RequestMethod.POST})
	public String index(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String,Object>();
		System.err.println("index"+map.keySet().size());
		map.put("res", 1);
		return GsonUtil.toJSONString(map);
	}
	
    @ResponseBody
    @RequestMapping(value="addClub.html",method = {RequestMethod.GET, RequestMethod.POST})
    public String addClub(String clubName,String clubManagerId,HttpServletRequest request){
    	Club club=new Club();
    	if(StringUtils.isBlank(clubName) || StringUtils.isBlank(clubManagerId)){
    		return resultVal();
    	}
    	Random random = new Random();
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数
        while(clubService.selectClubId(String.valueOf(rannum))>0){
        	rannum=(int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
        }
        club.setClubId(rannum);
    	club.setClubManagerId(Integer.valueOf(clubManagerId));
		club.setClubName(clubName);
		club.setClubSize(1);
		club.setClubNotice("公告");
		if(clubService.insertClub(club)>0){
			returnResult.setMsg("保存成功！");
			returnResult.setData(club);
		}else{
			returnResult.setError(true);
			returnResult.setMsg("保存失败");
		};
    	return resultVal();
    }

    
    @SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping(value="bindClub.html",method = RequestMethod.POST)
    public String bindClub(String clubId,String playerId,HttpServletRequest request){
    	
    	System.err.println("绑定俱乐部,IP地址:"+request.getLocalAddr()+"clubId:"+clubId+"------玩家ID:"+playerId);
    	if(StringUtils.isBlank(clubId) || StringUtils.isBlank(playerId)){
    		return resultVal();
    	}
    	Club club=clubService.selectClubById(clubId);
    	if(club==null){
    		returnResult.setError(true);
    		returnResult.setMsg("不存在此俱乐部！");
    		return resultVal();
    	}
    	ClubPlayerMapping mapping=new ClubPlayerMapping();
    	mapping.setClubId(Integer.parseInt(clubId));
    	mapping.setPlayerId(Integer.parseInt(playerId));
    	mapping.setAdvanceDiamond(club.getClubAdvanceDiamond());
    	if(clubService.insertClubMapping(mapping,club)>0){
    		returnResult.setData(club);
    		returnResult.setMsg("绑定成功!");
    	}else{
    		returnResult.setError(true);
    		returnResult.setMsg("绑定失败!");
    	}
    	return resultVal();
    }
    /**
     * 取消绑定
     * @param playerId
     * @return
     */
    @ResponseBody
    @RequestMapping(value="relieveBindClub.html",method = RequestMethod.POST)
    public BaseResult relieveBindClub(String playerId){
    	if(StringUtils.isNotBlank(playerId)){
    		if(clubService.deleteClubMapping(playerId)>0){
    			returnResult.setMsg("取消绑定成功!");
    		}else{
    			returnResult.setError(true);
    			returnResult.setMsg("取消绑定失败!");
    		}
    	}else{
    		returnResult.setError(true);
			returnResult.setMsg("玩家ID为空!");
    	}
    	return returnResult;
    }
    
    @SuppressWarnings("unchecked")
	@ResponseBody
    @RequestMapping(value="getBindClub.html",method = RequestMethod.POST)
    public String getBingClubInfo(String playerId){
    	if(StringUtils.isBlank(playerId)){
    		returnResult.setMsg("玩家Id为空");
    		returnResult.setError(true);
    		return resultVal();
    	}
    	returnResult.setData(clubService.selectClubByPlayerId(playerId));
    	return resultVal();
    }
    @ResponseBody
    @RequestMapping(value="getClubById.html",method = RequestMethod.POST)
    public String getClubInfoById(String clubId){
    	if(StringUtils.isNotBlank(clubId)){
    		returnResult.setData(clubService.selectClubById(clubId));
    	}
    	return resultVal();
    }
    /**
     * 查询玩家是否可添加管理员
     * @param playerId
     * @return
     */
    @ResponseBody
    @RequestMapping(value="searchPlayerInfo")
    public String searchPlayerInfo(String playerId){
    	Map<String,Object> map=new HashMap<>();
    	if(StringUtils.isNotBlank(playerId)){
    		Player player=clubService.selectPlayerInfo(playerId);
    		if(player!=null){
    			map.put("player", player);
    		}
    		Manager u=clubService.checkPlayerIsManager(playerId);
    		if(u!=null){
    			map.put("manager", u);
    			map.put("error", true);//表示该玩家无法添加管理员，已经拥有管理员身份
    		}
    	}
    	return GsonUtil.toJSONString(map);
    }
    /**
     * 添加代理
     * @param playerId
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="addAgent.html", method = {RequestMethod.GET,
            RequestMethod.POST})
    public String addAgent(String playerId,String agentAccount,String clubName,String managerType,@RequestParam Map<String, Object> para ,HttpServletRequest request){
    	 if(StringUtils.isBlank(playerId)) playerId=request.getParameter("playerId");
    	 if(StringUtils.isBlank(agentAccount)) playerId=request.getParameter("agentAccount");
    	 if(StringUtils.isBlank(clubName)) playerId=request.getParameter("clubName");
    	 if(StringUtils.isBlank(managerType)) playerId=request.getParameter("managerType");
         if(StringUtils.isBlank(playerId) || StringUtils.isBlank(agentAccount) ||StringUtils.isBlank(playerId)||StringUtils.isBlank(managerType)){
         	para.put("msg", "获取信息失败！请联系开发");
         	para.put("error", true);
         	return GsonUtil.toJSONString(para);
         }
         Player player=clubService.selectPlayerInfo(playerId);
         
         ClubPlayerMapping mapping=clubService.selectByPlayerId(playerId);
         if(mapping!=null){
        	 para.put("error",true);
        	 para.put("msg", "该玩家已绑定代理,请先退出绑定");
        	 return GsonUtil.toJSONString(para);
         }
    	 Manager agent=new Manager();
    	 agent.setManagerType(Integer.valueOf(managerType));
    	 agent.setUserAccount(agentAccount.trim());
    	 agent.setUserName(player.getNickName());
    	 agent.setPlayerId(playerId);
    	 int effectRow =clubService.addAgent(agent, para);
    	 if(effectRow>0){
    		 para.put("msg", "添加代理成功");
    		 para.put("agent", agent);
    	 }else{
    		 para.put("error", true);
    		 para.put("msg", "添加代理失败");
    	 }
    	return GsonUtil.toJSONString(para);
    }
    /**
     * 推送公告消息
     * @param msg
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="sendNoticeMsg.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public BaseResult addNotice(NoticeMsg msg,HttpServletRequest request){
    	Manager user=(Manager) request.getSession().getAttribute("loginUser");
    	if(user!=null && msg!=null && msg.getContent()!=null){
    			msg.setCreateUser(user.getId());
    			clubService.sendNoticeMsg(msg);
    			returnResult.setMsg("推送成功!");
    	}else{
			returnResult.setMsg("推送失败!");
			returnResult.setError(true);
		}
    	return returnResult;
    }
    /**
     * 清除玩家异常
     * @param playerId
     * @return
     */
    @ResponseBody
    @RequestMapping(value="clearPlayer.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public BaseResult clearPlayer(String playerId){
    	if(StringUtils.isNotBlank(playerId)){
    		clubService.clearPlayer(playerId);
    		returnResult.setMsg("清理成功!");
    	}else{
    		returnResult.setError(true);
    		returnResult.setMsg("玩家ID为空!");
    	}
    	return returnResult;
    }
    
    @RequestMapping(value="getApplication.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public String getApplication(Model model,@RequestParam Map param) throws UnsupportedEncodingException{
    	model.addAllAttributes(param);
    	model.addAttribute("list", clubService.getApplicationorm(param));
    	return "views/manager/application";
    }
    
    @ResponseBody
    @RequestMapping(value="upOrDownLevel.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public BaseResult upOrDownLevel(String managerId){
    	if(StringUtils.isNotBlank(managerId)){
    		if(clubService.upOrDownLevel(managerId)>0){
    			returnResult.setMsg("更新代理级别成功!");
    		}else{
    			returnResult.setError(true);
    			returnResult.setMsg("更新代理级别失败!");
    		}
    	}else{
    		returnResult.setError(true);
			returnResult.setMsg("获取代理ID失败!");
    	}
    	return returnResult;
    }
    @ResponseBody
    @RequestMapping(value="updateAdminDesc.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public BaseResult updateAdminDesc(@RequestParam Map<String,Object> map){
    	if(map.get("userId")!=null && map.get("desc")!=null){
    		if(clubService.updateAdminDesc(map)>0){
    			returnResult.setMsg("更新成功!");
    			return returnResult;
    		}
    	}
    	returnResult.setMsg("更新失败!");
    	returnResult.setError(true);
    	return returnResult;
    }
    @ResponseBody
    @RequestMapping(value="getManagerTable.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public Map getManagerTable(@RequestBody Map<String,Object> map){
    	if(map.get("limit")==null && map.get("offset")==null){
    		 map.put("offset", 1);
    	     map.put("limit", 10);
    	}
    	consumerService.getManagerTable(map);
    	return map;
    }
    @RequestMapping(value="managerInfo.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public String managerInfo(Model model,@RequestParam Map param) throws UnsupportedEncodingException{
    	model.addAllAttributes(param);
    	model.addAttribute("basePath",basePath());
    	return "views/manager/managerInfo2";
    }
    
    
    @RequestMapping(value="gameContro.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public String gameContro(Model model,@RequestParam Map param) throws UnsupportedEncodingException{
    	model.addAllAttributes(param);
    	model.addAttribute("basePath",basePath());
    	return "views/manager/gameContro";
    }
    
    @ResponseBody
    @RequestMapping(value="closeCreateRoom.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public BaseResult closeCreateRoom(@RequestParam Map map){
    	List<String> args=new ArrayList<String>();
		RequestModel requestModel=new RequestModel();
        requestModel.setCmd(com.jike.mahjong.model.RequestMethod.closeRoomCreate);
        args.add("0");//0表示关闭其他表示打开
        args.add(Constants.CLUB_DEFAULT_DIAMOND.toString());
        requestModel.setArgs(args);
        int resultUpdate = 0;
        String paraStr= GsonUtil.toJSONString(requestModel);
        String result= HttpUtil.PostWithJson(Constants.BACK_URL,paraStr);
        if(!result.equals("error")){
        	JsonParser jsonParser=new JsonParser();
        	JsonObject jsonObject=jsonParser.parse(result).getAsJsonObject();
        	resultUpdate=Integer.parseInt(String.valueOf(jsonObject.get("res")));
        }
        if(resultUpdate>0){
        	returnResult.setMsg("关闭创建房间成功!");
        }else{
        	returnResult.setError(true);
        	returnResult.setMsg("关闭创建房间失败!");
        	System.err.println("关闭创建房间失败!返回值:"+result);
        }
    	return returnResult;
    }
    
    @ResponseBody
    @RequestMapping(value="openCreateRoom.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public BaseResult openCreateRoom(@RequestParam Map map){
    	List<String> args=new ArrayList<String>();
		RequestModel requestModel=new RequestModel();
        requestModel.setCmd(com.jike.mahjong.model.RequestMethod.closeRoomCreate);
        args.add("1");//0表示关闭其他表示打开
        args.add(Constants.CLUB_DEFAULT_DIAMOND.toString());
        requestModel.setArgs(args);
        int resultUpdate = 0;
        String paraStr= GsonUtil.toJSONString(requestModel);
        String result= HttpUtil.PostWithJson(Constants.BACK_URL,paraStr);
        if(!result.equals("error")){
        	JsonParser jsonParser=new JsonParser();
        	JsonObject jsonObject=jsonParser.parse(result).getAsJsonObject();
        	resultUpdate=Integer.parseInt(String.valueOf(jsonObject.get("res")));
        }
        if(resultUpdate>0){
        	returnResult.setMsg("打开创建房间成功!");
        }else{
        	returnResult.setError(true);
        	returnResult.setMsg("打开创建房间失败!");
        	System.err.println("打开创建房间失败!返回值:"+result);
        }
    	return returnResult;
    }
    
    @ResponseBody
    @RequestMapping(value="selectNoticeMsg.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public Map selectNoticeMsg(@RequestParam Map map){
    	return clubService.getNoticeMsg(map);
    }
	@RequestMapping(value = "queryMessageList.html", method = {RequestMethod.GET,
	RequestMethod.POST})
    public String queryMessageList(@RequestParam Map map,Model model){
		model.addAllAttributes(clubService.getNoticeMsg(map));
    	return "views/title/messageShow";
    }
    
    @ResponseBody
    @RequestMapping(value="productsPage.html", method = {RequestMethod.GET,
            RequestMethod.POST},produces = "text/html;charset=utf8")
    public String productsPage(){
    	
    	return "views/";
    }
}
